import web
import simplejson
import uuid
import datetime
from models_webpy import *


class Hosts:
    def GET(self):
        dataset = Host().getAllByCurrentUser()

        if dataset:
            results = dataset
        else:
            results = {}

        return simplejson.dumps(results)


class Update:
    def POST(self):
        data = web.input()
        result = ''

        h = Host().getById(int(data.id))

        if h:
            # Update an existing row
            if 'hostname' in data:
                h.update(hostname=data.hostname)
                result = web.net.websafe(data.id)

            elif 'gateway_host' in data:
                h.update(gateway_host=data.gateway_host)
                result = web.net.websafe(data.gateway_host)

            elif 'gateway_port' in data:
                h.update(gateway_port=data.gateway_port)
                result = web.net.websafe(data.gateway_port)

            elif 'gateway_user' in data:
                h.update(gateway_user=data.gateway_user)
                result = web.net.websafe(data.gateway_user)

            elif 'authorized_ip' in data:
                h.update(authorized_ip=data.authorized_ip)
                result = web.net.websafe(data.authorized_ip)

            elif 'tunnel_status' in data:
                h.update(tunnel_status=data.tunnel_status)

                # Update host's log field on tunnel_status change
                now = datetime.datetime.now()
                formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
                if data.tunnel_status == 'ON':
                    h.update(log="Tunnel was turn ON at %s" % (formatted_now))
                elif data.tunnel_status == 'OFF':
                    h.update(log="Tunnel was turn OFF at %s" % (formatted_now))

                result = web.net.websafe(data.tunnel_status)

            return result


class Delete:
    def GET(self, id):
        if id.isdigit():
            h = Host().getById(int(id))
            if h:
                h.delete()


class New:
    def GET(self, groupID):

        tunnel_key = uuid.uuid4()
        obj = Host().create(groupID, tunnel_key=tunnel_key, hostname='host', gateway_host='gateway', gateway_user='user')
        result = {
            "id": obj.id,
            "group_id": obj.group_id,
            "tunnel_key": str(obj.tunnel_key),
            "hostname": obj.hostname,
            "tunnel_status": obj.tunnel_status,
            "gateway_port": obj.gateway_port,
            "gateway_host": obj.gateway_host,
            "gateway_user": obj.gateway_user
        }

        return simplejson.dumps(result)


class Broker:
    def GET(self, id):

        h = Host().getById(int(id))

        if h:
            import StringIO
            import tarfile
            import re

            #File object for on-the-fly tar.gz archive
            output = StringIO.StringIO()
            archive = tarfile.open(name=None, mode='w:gz', fileobj=output)

            #reading base template for configuration file and replace %replaceme% placeholder with tunnel_key
            data = open('broker/sshmein.conf').read()
            generated_conf_file = StringIO.StringIO(re.sub("%replaceme%", h.tunnel_key, data))

            #Create tarinfo object name and file size and add on-the-fly generated file to the archive
            tar_info = tarfile.TarInfo('broker/sshmein.conf')
            tar_info.size = len(generated_conf_file.getvalue())
            archive.addfile(tar_info, fileobj=generated_conf_file)

            #Adding other necessary files to the archive
            archive.add('broker/sshmein.sh')
            archive.add('broker/README-EN.txt')
            archive.add('broker/README-FR.txt')
            archive.add('broker/setup_passwordless_login.sh')

            #Closing file handle
            generated_conf_file.close()
            archive.close()

            #Getting archive content and closing handle
            contents = output.getvalue()
            output.close()

            #Streaming file to the browser
            web.header('Content-Type', 'application/x-gzip')
            web.header('Content-Disposition', 'attachment; filename="' + h.hostname + '_sshmein_broker.tar.gz"')
            return contents
